<?php

namespace App\Exceptions;

use App\Jobs\DingtalkException;
use ErrorException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use ParseError;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param Throwable $exception
     * @return void
     *
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {
        $message = env('APP_ENV').'-Error'.PHP_EOL;
        $message = $message.'Code: '.$exception->getCode().PHP_EOL;
        $message = $message.'Message: '.$exception->getMessage().PHP_EOL;
        $message = $message.'File: '.$exception->getFile().PHP_EOL;
        $message = $message.'Line: '.$exception->getLine().PHP_EOL;
        if (env('DING_ROBOT_ES')) {
            Queue::push(new DingtalkException($message),'',DingtalkException::QUEUE_NAME);
        }
        Log::error('ERROR', explode(PHP_EOL, $message));

        if ($exception instanceof ParseError
            ||$exception instanceof ErrorException
        ) {
            throw new \Error(trans('errorCode.50001'));
        }

        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  Request  $request
     * @param  Throwable $exception
     * @return Response|JsonResponse
     *
     * @throws Throwable
     */
    public function render($request, Throwable $exception)
    {
        return parent::render($request, $exception);
    }
}
